import { SettingDrawer, PageLoading } from "@ant-design/pro-layout";
import React, { useEffect, useState } from "react";
import { history, Link } from "umi";
import RightContent from "@/components/RightContent";
import Footer from "@/components/Footer";
import { CloseOutlined, LinkOutlined } from "@ant-design/icons";
import { getUserInfo } from "@/services/admin";
import defaultSettings from "../config/defaultSettings";
import routes from "../config/routes";
import moment from "moment";
import { Button, Space } from "antd";
import bgIcon from "../public/images/bg.png";

const isDev = process.env.NODE_ENV === "development";
const loginPath = "/admin/login";
/** 获取用户信息比较慢的时候会展示一个 loading */

export const initialStateConfig = {
  loading: <PageLoading />,
};
/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */

export async function getInitialState() {
  const fetchUserInfo = async () => {
    try {
      const res = await getUserInfo();
      // const res = {
      //   code:200,
      //   data:{
      //     user:{
      //       nickName:'历史'
      //     }
      //   }
      // }
      if (res.code === 200) {
        return res.data;
      }
      return {};
    } catch (error) {
      history.push(loginPath);
    }

    return undefined;
  }; // 如果不是登录页面，执行
  // console.log("history.location.pathname", history.location.pathname);
  console.log("loginPath", loginPath);

  if (history.location.pathname !== loginPath) {
    const res = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser: res.user,
      settings: defaultSettings,
      routes,
    };
  }

  return {
    fetchUserInfo,
    settings: defaultSettings,
    routes,
  };
} // ProLayout 支持的api https://procomponents.ant.design/components/layout

// 系统时间
const DateMoment = () => {
  const [date, setDate] = useState(
    moment(new Date()).format("YYYY年MM月DD日 HH:mm:ss")
  );
  useEffect(() => {
    setInterval(() => {
      setDate(moment(new Date()).format("YYYY年MM月DD日 HH:mm:ss"));
    }, 1000);
  });
  return <div className="date-moment">{date}</div>;
};

function flattern(arr) {
  const result = [];
  const func = (arr) => {
    arr.forEach((item) => {
      if (item.routes) {
        func(item.routes);
      } else {
        result.push(item);
      }
    });
  };
  func(arr);
  return result;
}

// 获取路由标题
const findTitle = (item) => {
  const arr = flattern(routes);
  const title = arr.find((i) => i.path === item.pathname)?.name;
  return title;
};

// 获取隐藏的菜单
const findIsHideInMenu = (item) => {
  const arr = flattern(routes);
  const hideInMenu = arr.find((i) => i.path === item.pathname)?.hideInMenu;
  console.log("hideInMenu===", hideInMenu);
  return hideInMenu;
};

const renderTagView = (initialState, setInitialState) => {
  const onRemove = (e, item, currentIndex) => {
    e.stopPropagation();

    // 如果删除了当前，则自动跳转到前一个/后一个
    const prev = initialState.tagViewList[currentIndex - 1];
    const next = initialState.tagViewList[currentIndex + 1];
    if (location.pathname.includes(item.pathname) && (prev || next)) {
      history.push(prev?.pathname || next?.pathname);
    }

    const tagViewList = initialState.tagViewList.filter(
      (sub) => sub.pathname !== item.pathname
    );

    setInitialState({
      ...initialState,
      tagViewList,
    });
    localStorage.setItem("tagViewList", JSON.stringify(tagViewList));
  };

  // const showTagViewList = initialState.tagViewList?.filter(
  //   (item) => !findIsHideInMenu(item)
  // );
  const showTagViewList = initialState.tagViewList;
  return (
    <div className="my-tag-view-btns">
      {showTagViewList?.map((item, index) => (
        <Button
          className="my-tag-view-btn"
          key={item.key}
          onClick={() => {
            history.push(item.pathname + item.search);
          }}
          type={
            location.pathname.includes(item.pathname) ? "primary" : "default"
          }
        >
          {findTitle(item)}
          {initialState.tagViewList.length !== 1 && index !==0 && (
            <CloseOutlined
              onClick={(e) => {
                onRemove(e, item, index);
              }}
            />
          )}
        </Button>
      ))}
    </div>
  );
};

export const layout = ({ initialState, setInitialState }) => {
  // console.log("initialState", initialState);

  return {
    // 自定义头内容的方法
    headerRender: () => {
      return (
        <div className="my-header-wrap">
          <div className="my-header">
            <img className="bg" src={bgIcon} alt="" srcset="" />

            <div className="other-info">
              <DateMoment />
              <RightContent />
            </div>
          </div>
          <div className="my-tag-view">
            {renderTagView(initialState, setInitialState)}
          </div>
        </div>
      );
    },
    // rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    // waterMarkProps: {
    //   content: initialState?.currentUser?.name,
    // },
    // footerRender: () => <Footer />,
    onPageChange: (e) => {
      console.log("e===", e);
      e.pathname = e.pathname.replace(/\/$/, ''); // 去掉前缀
      const { location } = history; // 如果没有登录，重定向到 login

      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
        return;
      }

      if (
        e.pathname === "/admin/login" || // 登录页不加入
        e.pathname === "/"
      ) {
        return;
      }
      const tagViewList = JSON.parse(localStorage.getItem("tagViewList")) || [];
      if (!tagViewList.length) {
        tagViewList.unshift(e);
      } else {
        const pathnames = tagViewList.map((item) => item.pathname);
        if (!pathnames.includes(e.pathname)) {
          // tagViewList.unshift(e);
          tagViewList.push(e);
        }
      }
      localStorage.setItem("tagViewList", JSON.stringify(tagViewList));
      setInitialState({
        ...initialState,
        tagViewList,
      });
    },
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children, props) => {
      // if (initialState?.loading) return <PageLoading />;
      return <>{children}</>;
    },
    ...initialState?.settings,
  };
};
